package com.gmrz.uap.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Wang Haifeng
 */
public class RequestResponseLoggingFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(RequestResponseLoggingFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化过滤器
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        // 创建自定义的包装类，用于包装请求和响应
        RequestWrapper requestWrapper = new RequestWrapper(httpRequest);
        ResponseWrapper responseWrapper = new ResponseWrapper(httpResponse);

        // 在处理请求之前，可以从包装类中获取请求报文
        String requestPayload = requestWrapper.getRequestPayload();
        log.info("请求报文: " + requestPayload);

        // 继续处理请求
        filterChain.doFilter(requestWrapper, responseWrapper);

        // 在处理响应之后，可以从包装类中获取响应报文
        String responsePayload = responseWrapper.getResponsePayload();
        log.info("响应报文: " + responsePayload);
    }

    @Override
    public void destroy() {
        // 销毁过滤器
    }
}